import GanttChart from './components/gantt_chart.tsx';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, InputNumber, message, Upload } from 'antd';
import './App.css';
import React, { useState } from 'react';

interface IItem {
  label: string;
  name: string;
  workAmount: number;
  unitDuration: number;
}

const App = () => {
  const [uploadFileName, setUploadFileName] = React.useState<string>('');
  const [parseLog, setParseLog] = useState<string[]>([]);
  const [freshGantt, setFreshGantt] = useState(1);

  const [inputValues, setInputValues] = useState([]);

  const inputItems: IItem[] = [
    { label: '柱钢筋绑扎', name: 'column_rebar', workAmount: 1, unitDuration: 0.164 },
    { label: '柱模板安装', name: 'column_formwork', workAmount: 1, unitDuration: 0.164 },
    { label: '梁、楼板模板安装', name: 'beam_slab_formwork', workAmount: 1, unitDuration: 0.164 },
    { label: '柱浇筑混凝土', name: 'column_concrete', workAmount: 1, unitDuration: 0.164 },
    { label: '梁、楼板钢筋绑扎', name: 'beam_slab_rebar', workAmount: 1, unitDuration: 0.164 },
    { label: '梁、楼板混凝土浇筑', name: 'beam_slab_concrete', workAmount: 1, unitDuration: 0.164 },
    { label: '养护', name: 'curing', workAmount: 1, unitDuration: 0.164 },
    { label: '拆模', name: 'remove_formwork', workAmount: 1, unitDuration: 0.164 },
  ];

  const handleInputChange = (key: string, value: number | null) => {
    setInputValues({
      ...inputValues,
      [key]: value,
    });
  };

  const inputFields = [];

  for (let i = 0; i < inputItems.length; i++) {
    inputFields.push(
      <>
        <div><span>{inputItems[i].label}</span></div>
        <div>工人数量:</div>
        <div>
          <InputNumber<number>
            style={{ width: 200 }}
            defaultValue={1}
            min={0}
            step="1"
            onChange={
              (value) => handleInputChange(inputItems[i].name + '_int_param', value)
            }
            stringMode
          />
        </div>
        <div>单位体积的工时:</div>
        <div>
          <InputNumber<number>
            style={{ width: 200 }}
            defaultValue={0.164}
            min={0}
            step="0.01"
            onChange={
              (value) => handleInputChange(inputItems[i].name + '_float_param', value)
            }
            stringMode
          />
        </div>
      </>,
    );
  }
  const props: UploadProps = {
    name: 'file',
    action: import.meta.env.VITE_HOST + '/upload',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        setUploadFileName(info.file.response.filename);
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };


  const handleParseIFC = () => {
    setParseLog([]);
    var url = `${import.meta.env.VITE_HOST}/process/${uploadFileName}?`;

    for (const key in inputValues) {
      url += `${key}=${inputValues[key]}&`;
    }
    url = url.slice(0, -1);

    const eventSource = new EventSource(url);
    eventSource.onmessage = (event) => {
      setParseLog((prevLog) => [...prevLog, event.data]);
    };

    eventSource.onerror = (error) => {
      console.error('EventSource failed:', error);
      eventSource.close();
      setFreshGantt(freshGantt + 1);
      // 发起甘特图请求
    };
  };
  const handleFresh = () => {
    setFreshGantt((freshGantt + 1));
  };

  return (
    <>
      <div className="flex flex-col gap-4">
        <span className="text-4xl">Upload and process an IFC file</span>
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>Click to Upload</Button>
        </Upload>
        {uploadFileName === '' ?
          null :
          <>
            <div className="grid grid-cols-5 gap-4 mr-auto">
              {inputFields}
            </div>
            <div>
              <Button type="primary" onClick={handleParseIFC}>解析{uploadFileName}</Button>
            </div>
            <div>
              <Button type="primary" onClick={handleFresh}>刷新甘特图</Button>
            </div>
            <ul>
              {parseLog.map((log, index) => (
                <li key={index}>{log}</li>
              ))}
            </ul>
          </>
        }
        <GanttChart fresh={freshGantt} />
      </div>
    </>
  );
};

export default App;
